package main.java.web.servlet;

import main.java.domain.User;
import main.java.utils.UploadUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@WebServlet("/uploadServlet")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        // 文件上传
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 设置缓冲区
        factory.setSizeThreshold(1024 * 1024 * 10);
        File uploadTemp = new File("D://uploadTemp");
        uploadTemp.mkdirs();
        factory.setRepository(uploadTemp);

        // 文件大小 100M
        upload.setFileSizeMax(1024 * 1024 * 100);

        // 字段存储
        Map<String, String> map = new HashMap<>();

        // 获取username
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        // 生成文件存储位置
        String path = UploadUtils.randomString(15);
        // 粗腰存储的文件名
        String filenames = "";

        try {
            List<FileItem> list = upload.parseRequest(req);
            for (FileItem item : list) {
                // 文件字段
                if (item.getName() != null && !"".equals(item.getName())) {
                    String filename = item.getName();
                    // 文件存储位置根目录
                    String rootPath = "D://software project/";

                    // 建立文件夹
                    File filepath = new File(rootPath + path);
                    if (!filepath.exists()) {
                        filepath.mkdirs();
                    }

                    filenames += rootPath+path+"/"+filename+";";

                    item.write(new File(filepath, filename));
                } else {
                    // 普通表单字段
                    map.put(item.getFieldName(), item.getString("utf-8"));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        req.setAttribute("save_task_map", map);
        req.setAttribute("id", user.getId());
        req.setAttribute("path", filenames.substring(0, filenames.length() - 1));

        if(user.getType().equals("TEACHER")){
            // 老师添加作业 转发到addTaskServlet
            req.getRequestDispatcher("/addTaskServlet").forward(req, res);
        }else if(user.getType().equals("STUDENT")){
            // 学上提交作业 转发到submitTaskServlet
            req.getRequestDispatcher("/submitTaskServlet").forward(req, res);
        }
    }
}
